<template>
    <!-- 页面-角色管理 -->
    <div class="innerPageTable-out-flex">
      <!-- 搜索区域 -->
      <SelfAdaption>
        <Form
          :model="searchForm"
          ref="searchForm"
          slot="adaption-bar"
          label-position="top"
          class="ivu-form-no-margin-bottom"
          inline
        >
          <template>
            <FormItem prop="addressCode" label="地址代码">
                <Input type="text" :maxlength="30" v-model.trim="searchForm['addressCode']" 
                    placeholder="请输入地址代码" clearable @on-enter="search">
                </Input>
            </FormItem>
            <FormItem prop="addressName" label="地址名称">
                <Input type="text" :maxlength="30" v-model.trim="searchForm['addressName']" 
                    placeholder="请输入地址名称" clearable @on-enter="search">
                </Input>
            </FormItem>
            <FormItem prop="addressEn" label="地址英文">
                <Input type="text" :maxlength="30" v-model.trim="searchForm['addressEn']" 
                    placeholder="请输入地址英文" clearable @on-enter="search">
                </Input>
            </FormItem>
            <FormItem prop="province" label="省份">
                <Input type="text" :maxlength="30" v-model.trim="searchForm['province']" 
                    placeholder="请输入省份" clearable @on-enter="search">
                </Input>
            </FormItem>
            <FormItem prop="city" label="城市">
                <Input type="text" :maxlength="30" v-model.trim="searchForm['city']" 
                    placeholder="请输入城市" clearable @on-enter="search">
                </Input>
            </FormItem>
            <FormItem prop="county" label="区县">
                <Input type="text" :maxlength="30" v-model.trim="searchForm['county']" 
                    placeholder="请输入区县" clearable @on-enter="search">
                </Input>
            </FormItem>
            <!-- 查询\重置按钮 -->
            <FormItem prop="button" class="search-solt-btn">
              <RPButton optType="search" @click="search" />
              <RPButton optType="reset" @click="reset" />
            </FormItem>           
          </template>
        </Form>
      </SelfAdaption>
      <InnerPageTable ref="searchTable" :config="tableConfig">
        <div slot="table-bar">
          <RPButton optType="create" @click="onOpenAddPage" v-permission="'ROLE_INDEX'" />
          <!--  -->
          <Dropdown @on-click="onDownMenu">
            <Button type="primary">
              批量操作
              <Icon type="ios-arrow-down"></Icon>
            </Button>
            <DropdownMenu slot="list">
              <DropdownItem name="disabled">删除</DropdownItem>
            </DropdownMenu>
          </Dropdown>
        </div>
      </InnerPageTable>
    </div>
</template>
<script>
import debounce from "lodash/debounce";
import { apiQueryTrainCityPage, apiTrainCityDeleteBatchOperate } from '@api/trip/standard/trainCity.js';
export default {
    name: 'trip-train-city',
    mixins: [],
    data() {
        return {
            title: '火车城市管理',
            searchForm: {    
                addressCode: '', //地址代码
                addressName: '', //地址名称
                addressEn: '', //地址英文
                // country: '', //国家
                province: '', //省份
                city: '', //城市
                county: '', //区县    
            }   
        }
    },
    watch: {},
    computed: {
    tableConfig() {
      return {
        border: true,
        loadDataFn: this.queryListByPage,
        columnsFn: () => {
          let columns = [
            {
              type: 'selection',
              width: 50,
              align: 'center'
            },
            {
              title: '地址代码',
              key: 'addressCode',
              width: 180,
              resizable: true,
              align: 'center',
              render: (h, params) => {
                let title = params.row['addressCode']
                return h(
                  'div',
                  { attrs: { class: 'ivu-table-cell ivu-table-cell-ellipsis', title: title } },
                  title
                )
              }
            },
            {
              title: '地址名称',
              key: 'addressName',
              width: 180,
              resizable: true,
              align: 'center',
              render: (h, params) => {
                let title = params.row['addressName']
                return h(
                  'div',
                  { attrs: { class: 'ivu-table-cell ivu-table-cell-ellipsis', title: title } },
                  title
                )
              }
            },
            {
              title: '地址英文',
              key: 'addressEn',
              resizable: true,
              align: 'center',
              render: (h, params) => {
                let title = params.row['addressEn']
                return h(
                  'div',
                  { attrs: { class: 'ivu-table-cell ivu-table-cell-ellipsis', title: title } },
                  title
                )
              }
            },
            {
              title: '国家',
              key: 'country',
              resizable: true,
              align: 'center',
              render: (h, params) => {
                let title = params.row['country']
                return h(
                  'div',
                  { attrs: { class: 'ivu-table-cell ivu-table-cell-ellipsis', title: title } },
                  title
                )
              }
            },
            {
              title: '省份',
              key: 'province',
              width: 180,
              resizable: true,
              align: 'center',
              render: (h, params) => {
                let title = params.row['province']
                return h(
                  'div',
                  { attrs: { class: 'ivu-table-cell ivu-table-cell-ellipsis', title: title } },
                  title
                )
              }
            },
            {
              title: '城市',
              key: 'city',
              width: 180,
              resizable: true,
              align: 'center',
              render: (h, params) => {
                let title = params.row['city']
                return h(
                  'div',
                  { attrs: { class: 'ivu-table-cell ivu-table-cell-ellipsis', title: title } },
                  title
                )
              }
            },
            {
              title: '区县',
              key: 'county',
              width: 180,
              resizable: true,
              align: 'center',
              render: (h, params) => {
                let title = params.row['county']
                return h(
                  'div',
                  { attrs: { class: 'ivu-table-cell ivu-table-cell-ellipsis', title: title } },
                  title
                )
              }
            },
            {
              title: this.$t('common.operating'),
              align: 'left',
              fixed: 'right',
              resizable: true,
              width: 150,
              render: (h, { row }) => {
                let data = []
                data = [
                {
                    text: '编辑',
                    handle: debounce(() => this.onOpenEditPage(row), 300)
                },
                {
                    text: '删除',
                    handle: debounce(() => this.onUpdate(row), 300)
                }
                ]
                return h('RowTools', {
                  props: {
                    data: data
                  }
                })
              }
            }
          ]
          return columns
        },
        autoFirst: false,
        rowClassNameFn: this.rowClassName // 自定义行样式
      }
    },
  },
  created: function() {
    
  },
  mounted() {
  },
  methods: {
    /**
     * 获取表格中选择的行ID
     */
    getSelectedIds() {
      let list = this.$refs['searchTable'].getSelectioned() || []
      let ids = []
      for (let u of list) {
        ids.push(u.id)
      }
      return ids
    },
    onDownMenu(name) {
      let ids = this.getSelectedIds();
      if (ids.length > 0) {
        const confirmMessages = {
          'disabled': '您确定要删除所选择的火车城市数据吗？',
        };
        const successMessages = {
          'disabled': '删除成功',
        };
        if (confirmMessages[name] ) {
          new $confirm(confirmMessages[name], this).then(() => {
            this.performBatchOperate(ids)
              .then(() => {
                this.$message.success({
                  content: successMessages[name],
                  duration: 3
                });
                this.search();
              })
              .catch(data => {
                this.$message.error({
                  content: data.message,
                  duration: 3
                });
              });
          });
        }
      }
    },

    performBatchOperate(ids) {
      return apiTrainCityDeleteBatchOperate({ ids: ids.join(',') });
    },
    // 自定义行样式
    rowClassName(row) {
      //关联的菜单中是否存在有效的hasEnabledMenu:1-存在,0-不存在
      if (row.hasEnabledMenu == 0) {
        return 'tableDisableStyle'
      }
    },
    async init() {
    //   let { userInfo } = $store.state[CoreModuleName]
    //   if (!userInfo) return
    //   this.category = userInfo.category
    //   // 根据当前租户查询数据
    //   // this.searchForm.tenantCode = userInfo.tenantCode
    //   const [appData] = await Promise.all([
    //     // valueSetAPI.getValueSetByCode('ROLE_TYPE'),
    //     searchAppListByTenantCode({
    //       pageNum: 1,
    //       pageSize: 200,
    //       condition: {
    //         tenantCode: userInfo.tenantCode
    //       }
    //     })
    //   ])
    //   console.log('appData :>> ', appData)
      // 查询列表
      this.search()
    },

    search(page = 1) {
      let searchParams = Object.assign({}, this.searchForm)
      this.$refs['searchTable'].load(searchParams, page)
    },
    /**
     * 重置搜索表单并重新执行搜索
     *
     * 重置搜索表单字段，并将搜索页码设为1，然后执行搜索操作。
     */
    reset() {
      // 检查searchForm引用是否存在
      if (this.$refs['searchForm'] && typeof this.$refs['searchForm'].resetFields === 'function') {
        // 重置搜索表单字段
        this.$refs['searchForm'].resetFields();
    
        // 检查search方法是否存在
        if (typeof this.search === 'function') {
          // 执行搜索，页码为1
          this.search(1);
        } else {
          console.error('The search method does not exist.');
        }
      } else {
        console.error('The searchForm reference does not exist or resetFields is not a function.');
      }
    },
    /**
     * 更新行数据状态函数
     *
     * @param row 需要更新的行数据对象
     * @param enabled 状态值，1表示启用，非1表示删除
     */
    onUpdate(row) {
      new $confirm('您确定要删除该行城市数据吗？', this).then(() => {
        // enabled 0 删除
        apiTrainCityDeleteBatchOperate({ ids: row.id + '' })
          .then(res => {
            this.$message.success({
              content: '修改成功',
              duration: 3
            })
            this.search()
          })
          .catch(data => {
            this.$message.error({
              content: data.message,
              duration: 3
            })
          })
      })
    },
    onDel(row) {
    //   new $confirm('您确定要删除该行差标职级数据吗？', this).then(() => {
    //     apiStandardPositionBatchOperate({ ids: row.id + '', enabled: '2' })
    //       .then(res => {
    //         this.$message.success({
    //           content: this.$t('module.orgManage.deleteSuccess'),
    //           duration: 3
    //         })
    //         this.search()
    //       })
    //       .catch(data => {
    //         this.$message.error({
    //           content: data.message,
    //           duration: 3
    //         })
    //       })
    //   })
    },
    onOpenEditPage(row) {
      new this.$sidelipPage(
        () => import('./trainCityDetail.vue'),
        {
          props: {
            TrainCity: Object.assign({},row),
          },
          isActionTop: false
        },
        data => {
          data && this.search()
        }
      )
    },
    onOpenAddPage: debounce(function() {
      new this.$sidelipPage(
        () => import('./trainCityDetail.vue'),
        {
          props: { 
            disabled: false
          },
          isActionTop: false
        },
        data => {
          data && this.search()
        }
      )
    }, 300),

    queryListByPage({ responseProcess, param }) {
      console.log('param :>> ', param)
      return apiQueryTrainCityPage(param).then(data => {
        console.log('data :>> ', data)
        if (data.success) {
            if(data.data != null){
                responseProcess(data.data)
            }else{
                responseProcess({ records: [] })
            }
        } else {
          this.$message.error({
            content: data.message || '未查询到火车城市信息',
            duration: 3
          })
          responseProcess({ records: [] })
        }
      })
    }
  }
}

</script>

